import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

def fourier_denoise(image, cutoff_frequency):
    # 将图像转换为频率域
    f = np.fft.fft2(image)
    fshift = np.fft.fftshift(f)
    
    # 创建一个与图像大小相同的掩码，中心为低通滤波区域
    rows, cols = image.shape
    crow, ccol = rows // 2, cols // 2
    mask = np.zeros((rows, cols), np.uint8)
    mask[crow - cutoff_frequency:crow + cutoff_frequency, ccol - cutoff_frequency:ccol + cutoff_frequency] = 1
    
    # 应用低通滤波器
    fshift_filtered = fshift * mask
    
    # 将过滤后的频率域图像转换回空间域
    f_ishift = np.fft.ifftshift(fshift_filtered)
    img_back = np.fft.ifft2(f_ishift)
    img_back = np.abs(img_back)
    
    return img_back

def denoise_image(image, cutoff_frequency):
    # 分别对每个通道进行去噪
    denoised_channels = []
    for i in range(3):
        channel = image[:, :, i]
        denoised_channel = fourier_denoise(channel, cutoff_frequency)
        denoised_channels.append(denoised_channel)
    
    # 合并去噪后的通道
    denoised_img = np.stack(denoised_channels, axis=2)
    
    # 将结果转换为合适的数据类型和范围
    denoised_img = np.clip(denoised_img, 0, 255).astype(np.uint8)
    
    return denoised_img

def update(val):
    cutoff_frequency = slider.val
    denoised_img = denoise_image(original_img, cutoff_frequency)
    ax.imshow(cv2.cvtColor(denoised_img, cv2.COLOR_BGR2RGB))
    fig.canvas.draw_idle()

# 读取图像
image_path = "image.png"  # 替换为您的图片路径
original_img = cv2.imread(image_path, cv2.IMREAD_COLOR)

# 创建一个窗口来显示图像和滑块
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
denoised_img = denoise_image(original_img, 30)  # 初始去噪
ax.imshow(cv2.cvtColor(denoised_img, cv2.COLOR_BGR2RGB))

# 创建一个滑块来调整截止频率
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
slider = Slider(axfreq, 'Cutoff Frequency', 1, 2000, valinit=30, valstep=1)

# 注册滑块事件的回调函数
slider.on_changed(update)

plt.show()
